#include "R6.h"
#include "mpx_supt.h"
#include "R3.H"
#include "R4.H"
#include "PCB.H"
#include "COMMANDH.H"
#include <dos.h>
#include <time.h>
#include <string.h>

/*Function to load the command handler as a process with a custom stack
 *
 */
void load_comhan() {
	//CODE ADAPTED FROM "LOAD_PROCS" of R3
	pcb *comhan_pcb;
	context *comhan_ctxt;
	comhan_pcb = setup_PCB("Command", PROC_CLASS_SYS, 127);
	if(comhan_pcb != NULL){
		//redefine comhan stack as 4k, redefine stack_top accordingly
		comhan_pcb->stack_base = (unsigned char *)sys_alloc_mem(sizeof(unsigned char)*4096);
		comhan_pcb->stack_top = comhan_pcb->stack_base + 4097 - sizeof(context);
		
		comhan_ctxt = (context*) comhan_pcb->stack_top;
		comhan_ctxt->IP = FP_OFF(&command_handler);
		comhan_ctxt->CS = FP_SEG(&command_handler);
		comhan_ctxt->FLAGS = 0x200;
		comhan_ctxt->DS = _DS;
		comhan_ctxt->ES = _ES;
		insert_pcb(comhan_pcb, PROC_STATE_READY, PROC_NOT_SUSP);
	}
	else {
		//ERROR HANDLING IF NECESSARY - UNRECOVERABLE?
		//could try load_comhan again lol
	}
}

/*Function to load the idle process
 *
 */
void load_idle() {
	pcb *idle;
	int resume_err;
	load_program("IDLE", -128);
	idle = find_pcb("IDLE");
	if (idle != NULL) {
		resume_err = resume_pcb("IDLE", "\0");//removed the sys class check from resume - change this later
		//add resume_err error handling if necessary
		//this might not be needed//insert_pcb(idle, PROC_STATE_READY, PROC_NOT_SUSP);
		idle->type = PROC_CLASS_SYS;
	}
}

void terminate_new() {
	int in_buff_size = 80;
	char buff_response[80];
	printf("Are you sure you wish to terminate MPX? (y/n)\n");
	sys_req(READ, TERMINAL, buff_response, &in_buff_size);
	if (*buff_response == 'y')
		terminate_confirmed_new();
	return;
}

void terminate_confirmed_new() {
	printf("MPX is terminating");
	sleep(1);
	printf(".");
	sleep(1);
	printf(".");
	sleep(1);
	printf(".\n");
	printf("Goodbye!\n");
	terminate_cleanup();
	mpx_io_cleanup();
	sys_exit();
}